package com.t.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.t.pojo.Drug;
import com.t.pojo.Msg;
import com.t.pojo.Sale;
import com.t.service.saleService;
import com.t.util.ToolsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sale")
public class saleController {
    @Autowired
    @Qualifier("saleServiceImpl")
    saleService service;
    @RequestMapping("/toSaleRecord")
    public String toSaleRecord(){
        return "StatisticalReport/SaleRecord";
    }
    @ResponseBody
    @RequestMapping("/findSaleAll")
    public Msg findSaleAll(@RequestParam(value = "pn",defaultValue = "1")Integer pn){
        PageHelper.startPage(pn,5);
        List<Sale> sales = service.findSaleAll();
        PageInfo page = new PageInfo(sales,5);
        return Msg.success().add("PageInfo",page);
    }
    @ResponseBody
    @RequestMapping("/findSaleByNameDate")
    public Msg  findSaleByNameDate(@RequestParam(value = "dname",required = false,defaultValue = "")String dname,
                                   @RequestParam(value = "startDate",required = false,defaultValue = "")String startDate,
                                   @RequestParam(value = "endDate",required = false,defaultValue = "")String endDate) throws ParseException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        ToolsMapper mapper = context.getBean("toolsMapper", ToolsMapper.class);
        HashMap  map=new HashMap();
        Date date=null;
        Date date1=null;
        if(!startDate.equals("")){
             date=mapper.stringToDate(startDate);
        }
        if(!endDate.equals("")){
             date1=mapper.stringToDate(endDate);
        }
        map.put("dname",dname);
        map.put("startDate",date);
        map.put("endDate",date1);
        List<Sale> sales = service.findSaleByNameDate(map);
        PageHelper.startPage(1,50);
        PageInfo page = new PageInfo(sales,5);
        return Msg.success().add("PageInfo",page);
    }
    @ResponseBody
    @RequestMapping("/deleteSaleByNums")
    public Msg deleteSaleByNums(String nums){
        String[] split = nums.split("-");
        ArrayList<String> list = new ArrayList<>();
        for (String s : split) {
            list.add(s);
        }
        service.deleteSaleByNums(list);
        return Msg.success();
    }
}
